import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'
const state = {
  token: getToken(), //从缓存中读取token
  userInfo: {},
  routes: constantRoutes   //静态路由的数组
}
const mutations = {
  setToken(state, token) {
    state.token = token
    //同步到缓存
    setToken(token)
  },
  //removeToken删除vuex中的token
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 修改数据
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...newRoutes, ...constantRoutes]
  }
}
const actions = {
  // 调用接口  接收数据
  async login(context, data) {
    const token = await login(data)
    // 返回一个token
    context.commit('setToken', token)
  },
  // 获取用户信息的接口
  async getUserInfo(context) {
    const res = await getUserInfo()
    context.commit('GETUSERINFO', res)
    return res  //返会数据
  },
  // 退出登录
  logout(context) {
    context.commit('removeToken')  //删除token
    context.commit('GETUSERINFO', {})  //删除用户的信息
    // 重置路由
    resetRouter()
  }
}
export default {
  namespaced: true,  //开启命名空间
  state,
  mutations,
  actions,
}
